package questions;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * ByteBuffer:
 *   读写指针共用，写入后需要调用flip()
 *
 * ByteBuf:
 *   读指针 写指针 分离
 *   不用flip
 *
 *
 * @Author: Administrator
 * @Date: 2023/4/19 10:15
 */

public class Buffer {



    @Test
    public void  ByteBuffer() throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put( "127".getBytes(StandardCharsets.UTF_8));
        System.out.println(byteBuffer);
        File f=new File("D://111.txt");
        System.out.println(f.getAbsolutePath());
        f.delete();
        System.out.println(f.createNewFile());
        f.setWritable(true);
        FileChannel fileOutputStream =new FileOutputStream(f).getChannel();
        //flip不调用写不出去
        byteBuffer.flip();
        System.out.println(byteBuffer);
        fileOutputStream.write(byteBuffer);
        fileOutputStream.close();
        fileOutputStream.close();


    }

    @Test
    public void ByteBuf() throws IOException {
        ByteBuf byteBuffer = ByteBufAllocator.DEFAULT.buffer(1024);

        byteBuffer.writeBytes( "127".getBytes(StandardCharsets.UTF_8));
        System.out.println(byteBuffer);
        File f=new File("D://222.txt");
        System.out.println(f.getAbsolutePath());
        f.delete();
        System.out.println(f.createNewFile());
        f.setWritable(true);
        FileChannel fileOutputStream =new FileOutputStream(f).getChannel();
        //flip不调用,没有这个方法
//        byteBuffer.flip();
        System.out.println(byteBuffer);
        fileOutputStream.write(byteBuffer.nioBuffer());
        fileOutputStream.close();
        fileOutputStream.close();

    }

}

